/**
 * 
 */
package com.alkandros.myloke.activities;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.alkandros.myloke.R;
import com.alkandros.myloke.activities.BaseActivity.LocationCallBack;
import com.alkandros.myloke.adapters.PlacesAdapter;
import com.alkandros.myloke.managers.ApiManager;
import com.alkandros.myloke.managers.ApiManager.ApiResponseListner;
import com.alkandros.myloke.managers.AppPreferenceManager;
import com.alkandros.myloke.managers.HeaderManager;
import com.alkandros.myloke.models.NearByModel;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;

/**
 * @author Jiju Induchoodan
 * 
 */
public class NearbyActivity extends BaseActivity implements OnClickListener,
		LocationCallBack {

	private RelativeLayout relativeLayoutHeader;
	private HeaderManager headerManager;
	private ArrayList<NearByModel> arrayModel = new ArrayList<NearByModel>();
	private PlacesAdapter adapter;
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nearby);

		relativeLayoutHeader = (RelativeLayout) findViewById(R.id.relativeLayoutHeader);
		listView = (ListView) findViewById(R.id.listView);
		headerManager = new HeaderManager(NearbyActivity.this);
		headerManager.getHeader(relativeLayoutHeader);

		headerManager.getButtonRight().setVisibility(View.INVISIBLE);
		headerManager.getTitle().setVisibility(View.INVISIBLE);
		headerManager.getImageLeft().setOnClickListener(this);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
						
						if(mMap!=null)
						{
							//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()),13));
							double latitude =arrayModel.get(arg2).getLatitude();
							double longitude =arrayModel.get(arg2).getLongitude();
							mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),13));
						//	locationCallBack.locationObjectReceived(location);
						}
					}
		});
	}

	private void callApi(Location location) {
		if (location != null) {
			arrayModel = new ArrayList<NearByModel>();
			adapter = new PlacesAdapter(NearbyActivity.this,arrayModel);
			mMap.clear();
			apiManager = new ApiManager(NEARBY_URL + "lat="
					+ location.getLatitude() + "&long="
					+ location.getLongitude() + "&faith="
					+ AppPreferenceManager.getFaith(this) + "&mile="
					+ AppPreferenceManager.getMiles(this), this, true);
			apiManager.setApiResponseListener(new ApiResponseListner() {

				@Override
				public void dataDownloadedSuccessfully(JSONObject response) {
					NearByModel model = new NearByModel();
					try {
						JSONArray organisations = response
								.getJSONArray(ORGANIZATIONS);
						for (int i = 0; i < organisations.length(); i++) {
							JSONObject jitem = organisations.getJSONObject(i);
							model = new Gson().fromJson(jitem.toString(),
									NearByModel.class);

							arrayModel.add(model);
							mMap.addMarker(new MarkerOptions()
							.position(new LatLng(arrayModel.get(i).getLatitude(),(arrayModel.get(i).getLongitude())
							 ))
							 .title(arrayModel.get(i).getName())
							 .snippet(arrayModel.get(i).getAddress()));
						}

					
						Log.e("", "Array size" + arrayModel.size());
						adapter = new PlacesAdapter(NearbyActivity.this,
								arrayModel);
						listView.setAdapter(adapter);

					} catch (Exception e) {
						Log.e("", "Parsing error" + e.getMessage());
						listView.setAdapter(adapter);
					}
				}

				@Override
				public void dataDownloadedFailed(String error) {
					Log.e("", "Error Response" + error);
				//	adapter.notifyDataSetChanged();
					listView.setAdapter(adapter);
				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		if (v == headerManager.getImageLeft()) {
			Intent intent = new Intent(NearbyActivity.this,
					SettingsActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void locationObjectReceived(Location location) {
		callApi(location);
	}
}
